package com.hzw.net.utils

import android.app.Activity
import android.content.Context
import android.graphics.Color
import android.os.Build
import android.view.*
import android.widget.FrameLayout
import com.hzw.core.Rom
import java.lang.reflect.Field
import java.lang.reflect.Method


/**
 * Copyright (c) 2019, 四川绿源集科技有限公司 All rights reserved.
 * author：HuaZhongWei
 * date：2019/7/17
 * description：
 */
object StatusBarUtils {

    private const val TAG_MARGIN_ADDED = "marginAdded"

    /**
     * 设置状态栏颜色
     *
     * @param activity
     * @param color
     */
    fun setStatusBarColor(activity: Activity, color: Int) {
        val window = activity.window
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { //5.0及以上
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
            window.statusBarColor = color
        } else {
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
            val systemContent = activity.findViewById<ViewGroup>(android.R.id.content)
            val statusBarView = View(activity)
            val lp = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                getStatusBarHeight(activity)
            )
            statusBarView.setBackgroundColor(color)
            systemContent.getChildAt(0).fitsSystemWindows = true
            systemContent.addView(statusBarView, 0, lp)
        }
    }

    /**
     * 状态栏透明
     *
     * @param activity
     */
    fun setStatusBarTranslucent(activity: Activity) {
        //设置透明时，需要在适当的位置加上 android:fitsSystemWindows="true"
        val window = activity.window
        when {
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP -> { //5.0及以上
                window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS or WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
                window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
                window.statusBarColor = Color.TRANSPARENT
            }
            else -> { //4.4到5.0
                val localLayoutParams = window.attributes
                localLayoutParams.flags = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS or localLayoutParams.flags
            }
        }
    }

    fun setStatusBarFontAndIconColor(activity: Activity, isDark: Boolean) {
        when {
            Rom.isXiaomi() -> {
                setStatusBarFontAndIconColorForMiUI(activity, isDark)
            }
            Rom.isMeizu() -> {
                setStatusBarFontAndIconColorForFlymeUI(activity, isDark)
            }
            else -> { //其他情况
                setStatusBarFontAndIconColorForCommon(activity, isDark)
            }
        }
    }


    /**
     * 通用机型
     * 设置状态栏文字图标是否为黑色
     *
     * @param activity
     * @param isDark   是否黑色
     */
    fun setStatusBarFontAndIconColorForCommon(
        activity: Activity,
        isDark: Boolean
    ): Boolean {
        return try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                val window = activity.window
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
                val decorView = window.decorView
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                    val controller = decorView.windowInsetsController
                    if (isDark) {
                        controller?.setSystemBarsAppearance(
                            WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS,
                            WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS
                        )
                    } else {
                        controller?.setSystemBarsAppearance(
                            0,
                            WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS
                        )
                    }
                } else {
                    var vis = decorView.systemUiVisibility
                    vis = if (isDark) {
                        vis or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
                    } else {
                        vis and View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR.inv()
                    }
                    decorView.systemUiVisibility = vis
                }
            }
            true
        } catch (e: Exception) {
            e.printStackTrace()
            false
        }
    }

    /**
     * 针对小米UI
     * 设置状态栏文字图标是否为黑色
     *
     * @param activity
     * @param isDark   是否黑色
     */
    fun setStatusBarFontAndIconColorForMiUI(
        activity: Activity,
        isDark: Boolean
    ): Boolean {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val window = activity.window
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
            val decorView = window.decorView
            var vis = decorView.systemUiVisibility
            vis = if (isDark) {
                vis or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
            } else {
                vis and View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR.inv()
            }
            decorView.systemUiVisibility = vis
        } else {
            val clazz: Class<out Window?> = activity.window.javaClass
            try {
                var darkModeFlag = 0
                val layoutParams = Class.forName("android.view.MiuiWindowManager\$LayoutParams")
                val field: Field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE")
                darkModeFlag = field.getInt(layoutParams)
                val extraFlagField: Method = clazz.getMethod(
                    "setExtraFlags",
                    Int::class.javaPrimitiveType,
                    Int::class.javaPrimitiveType
                )
                extraFlagField.invoke(
                    activity.window,
                    if (isDark) darkModeFlag else 0,
                    darkModeFlag
                )
            } catch (e: java.lang.Exception) {
                e.printStackTrace()
                return false
            }
        }
        return true
    }

    /**
     * 针对魅族 Flyme UI
     * 设置状态栏文字图标是否为黑色
     *
     * @param activity
     * @param isDark   是否黑色
     */
    fun setStatusBarFontAndIconColorForFlymeUI(
        activity: Activity,
        isDark: Boolean
    ): Boolean {
        return try {
            val window = activity.window
            val lp = window.attributes
            val darkFlag =
                WindowManager.LayoutParams::class.java.getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON")
            val meizuFlags =
                WindowManager.LayoutParams::class.java.getDeclaredField("meizuFlags")
            darkFlag.isAccessible = true
            meizuFlags.isAccessible = true
            val bit = darkFlag.getInt(null)
            var value = meizuFlags.getInt(lp)
            value = if (isDark) {
                value or bit
            } else {
                value and bit.inv()
            }
            meizuFlags.setInt(lp, value)
            window.attributes = lp
            true
        } catch (e: Exception) {
            e.printStackTrace()
            false
        }
    }

    /**
     * 获取状态栏高度
     *
     * @return
     */
    fun getStatusBarHeight(context: Context): Int {
        var statusBarHeight1 = -1
        //获取status_bar_height资源的ID
        val resources = context.resources
        val resourceId = resources.getIdentifier("status_bar_height", "dimen", "android")
        if (resourceId > 0) {
            //根据资源ID获取响应的尺寸值
            statusBarHeight1 = resources.getDimensionPixelSize(resourceId)
        }
        return statusBarHeight1
    }

    /**
     * 代码实现android:fitsSystemWindows
     *
     * @param activity
     */
    fun setRootViewFitsSystemWindows(
        activity: Activity,
        fitSystemWindows: Boolean
    ) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            val winContent = activity.findViewById<ViewGroup>(android.R.id.content)
            if (winContent.childCount > 0) {
                val rootView = winContent.getChildAt(0) as ViewGroup
                if (rootView != null) {
                    rootView.fitsSystemWindows = fitSystemWindows
                }
            }
        }
    }

    /**
     * 添加根布局与状态栏一样高的MarginTop
     * @param activity
     */
    fun addMarginTopWithStatusBarHeight(activity: Activity) {
        val window = activity.window
        val contentView =
            window.findViewById<ViewGroup>(Window.ID_ANDROID_CONTENT)
        val child = contentView.getChildAt(0)
        if (TAG_MARGIN_ADDED != child.tag) {
            val params =
                child.layoutParams as FrameLayout.LayoutParams
            // 添加的间隔大小就是状态栏的高度
            params.topMargin += getStatusBarHeight(activity)
            child.layoutParams = params
            child.tag = TAG_MARGIN_ADDED
        }
    }

    /**
     * 移除根布局与状态栏一样高的MarginTop
     * @param activity
     */
    fun removeMarginTopWithStatusBarHeight(activity: Activity) {
        val window = activity.window
        val contentView =
            window.findViewById<ViewGroup>(Window.ID_ANDROID_CONTENT)
        val child = contentView.getChildAt(0)
        if (TAG_MARGIN_ADDED == child.tag) {
            val params =
                child.layoutParams as FrameLayout.LayoutParams
            // 移除的间隔大小就是状态栏的高度
            params.topMargin -= getStatusBarHeight(activity)
            child.layoutParams = params
            child.tag = null
        }
    }
}